﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Owin;
using Sharp.Portal.Mvc.OAuth.Sharp.Server;
using Sharp.Portal.Owin;

namespace Sharp.Services.OAuth
{
	public partial class Startup
	{
	    public void ConfigureAuth(IAppBuilder app)
	    {
	        app.CreatePerOwinContext<SharpUserManager>(SharpUserManager.Create);
	        app.CreatePerOwinContext<SharpSignInManager>(SharpSignInManager.Create);

	        app.UseCookieAuthentication(new CookieAuthenticationOptions
	        {
	            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
	            LoginPath = new PathString("/Login"),
	            Provider = new CookieAuthenticationProvider
	            {
	                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<SharpUserManager, SharpUser, int>(
	                    TimeSpan.FromMinutes(30),
	                    (manager, user) => user.GenerateUserIdentityAsync(manager),
	                    id => int.Parse(id.GetUserId()))
	            },
	            CookieHttpOnly = true,
	            CookieName = "__SharpTicketSid",
	            SlidingExpiration = true,
	            ExpireTimeSpan = TimeSpan.FromMinutes(30)
	        });

            // 使应用程序可以使用不记名令牌来验证用户身份
            app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
	        {
	            AuthenticationType = "Bearer",
	            TokenEndpointPath = new PathString(Setting.EndPointConfig.TokenEndpointPath),
	            Provider = new SharpOAuthAuthorizationServerProvider(),
	            AuthorizeEndpointPath = new PathString(Setting.EndPointConfig.AuthorizeEndpointPath),
	            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
	            RefreshTokenProvider = new SharpAuthenticationTokenProvider()
	            {
	                TokenType = "RefreshToken",
	                TokenKeepingPredicate = data => data.GrantType == Setting.GrantTypes.RefreshToken,
	                ExpireTimeSpan = TimeSpan.FromDays(60)
	            },
	            AccessTokenProvider = new SharpAuthenticationTokenProvider()
	            {
	                TokenType = "AccessToken",
	                ExpireTimeSpan = TimeSpan.FromHours(2)
	            },
	            AuthorizationCodeProvider = new SharpAuthenticationTokenProvider()
	            {
	                TokenType = "AuthorizationCode",
	                ExpireTimeSpan = TimeSpan.FromMinutes(15),
	                RemoveWhenReceive = true
	            },


	            AllowInsecureHttp = true

	        });
        }

    }
}